import {computed, nextTick, ref} from "vue";
import {File} from './useFiles';
import {setLyric} from "./useLyric";

const isPlayerShow = ref(false);
const playing = ref(false);
const playingFile = ref<File>();
const current = ref(0);
const player = new Audio();
const handleTimeUpdate = () => {
    current.value = player.currentTime;
}
const handleEnd = () => {
    playing.value = false;
    current.value = player.currentTime = 0;
}
player.addEventListener('timeupdate', handleTimeUpdate)
player.addEventListener('ended', handleEnd)

const play = async (file: File) => {
    isPlayerShow.value = true;
    playingFile.value = file;
    playing.value = true;
    current.value = 0;
    player.setAttribute('src', `file://${file.path}`);
    player.play()
    setLyric(file.lyric || '');
    console.log(isPlayerShow.value);
};

const playCurrent = (current: number) => {
    player.currentTime = current;
    // @ts-ignore
    if (current >= playingFile.value.meta.format.duration) {
        stop();
    }
};

const pause = () => {
    player.pause();
    playing.value = false;
};

const resume = () => {
    player.play();
    playing.value = true;
}
const stop = () => {
    playing.value = false;
    player.pause();
    player.currentTime = 0;
};

const duration = computed(() => {
    return playingFile.value?.meta?.format.duration || 0;
});

export {
    isPlayerShow,
    playingFile,
    playing,
    current,
    duration,
    play,
    pause,
    stop,
    resume,
    playCurrent
}
